package com.momalib.ning2_nocode.controllers;

import com.momalib.ning2_nocode.beans.NncProjectConfig;
import com.momalib.ning2_nocode.beans.NncTmplConfig;
import com.momalib.ning2_nocode.config.ApiResponse;
import com.momalib.ning2_nocode.config.NncConfig;
import com.momalib.ning2_nocode.services.ConfigParseService;
import com.momalib.ning2_nocode.services.TemplateParseService;
import com.momalib.ning2_nocode.utils.CommonFileUtil;
import com.momalib.ning2_nocode.utils.CommonUtils;
import lombok.extern.log4j.Log4j2;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Log4j2
@RestController
public class IndexController {

    @Autowired
    ConfigParseService configParseService;

    @Autowired
    TemplateParseService templateParseService;

    @Autowired
    NncConfig nncConfig;

    @GetMapping("/ping")
    public ApiResponse ping() {
        return ApiResponse.ok();
    }

    @PostMapping("/uploadZip")
    public ApiResponse uploadZip(@RequestParam("files") MultipartFile[] files) throws IOException, ZipException {
        if (files.length != 1) {
            return ApiResponse.error("只能上传一个压缩文件");
        }
        String cachePath = nncConfig.getCacheFilePath();
//        System.out.println(tmpPath);
        File file = CommonFileUtil.multipartFile2File(files[0], cachePath);
        ZipFile zip = new ZipFile(file);
        zip.extractAll(cachePath);

        NncProjectConfig projectConfig = configParseService.analyseProjectConfig(cachePath + "/" + file.getName().split("\\.")[0]);
        configParseService.handleProjectBuild(projectConfig);

        return ApiResponse.ok();
    }

    @PostMapping("/buildTemplate")
    public ApiResponse buildTemplate(@RequestParam("name") String tmplName) throws IOException, ZipException {
        String tmplPath = nncConfig.getTmplFilePath() + "/" + tmplName;
        File tmplDir = new File(tmplPath);
        if (!tmplDir.exists() || !tmplDir.isDirectory()) {
            return ApiResponse.error("模板目录不存在");
        }

        String tmplRootPath = tmplDir.getAbsolutePath();
        NncTmplConfig tmplConfig = templateParseService.analyseTmplConfig(tmplRootPath);
        templateParseService.handleTmplBuild(tmplRootPath, tmplConfig);

        return ApiResponse.ok();
    }


}
